<?php


namespace app\controller\api;


use app\base\BaseEncryptController;
use app\factory\wxPay\WxParam;
use app\libs\Oss;
use app\libs\Util;
use app\model\goods\GoodsAttributeModel;
use app\model\goods\GoodsCommonModel;
use app\model\goods\GoodsModel;
use app\model\goods\GoodsTypeModel;
use app\model\order\OrderItemModel;
use app\model\store\StoreModel;
use app\model\user\UserCartModel;
use app\model\user\UserCollectUpModel;
use think\Image;
use think\Request;

class Goods extends BaseEncryptController
{

    protected function initialize()
    {
        parent::initialize();
        $this->model = new GoodsModel();
    }

    /**
     * 商品详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDetail(Request $request)
    {
        $goods_id = $request->param("goods_id");
        $bean = $request->param("bean");
        $is_bean = false;
        if ($bean == 'bean') {
            $is_bean = true;
        }
        $userInfo = $this->currentUser;//登录信息
        if (!isset($userInfo['user_id'])) {
            $userInfo['user_id'] = 0;
        }
        $goods = $this->model->getDetail($goods_id, $userInfo['user_id'], $is_bean);
        $cart_list = UserCartModel::getCartNumArr($userInfo['user_id'], $goods_id);
        $goods_attr_model = new GoodsAttributeModel();
        $attr_list = $goods_attr_model->getAttrList($goods_id);
        $goods_common_model = new GoodsCommonModel();
        $goods_common_list = $goods_common_model->getCommonGoods($goods_id, [], true);
        $goods_attr_arr_temp = [];
        $goods_attr_ids = [];
        $first_attribute_ids = [];
        $goods_common_list_out = [];
        foreach ($goods_common_list as $index => $value) {
            $attr_ids = $value['attribute_ids'];
            $attr_ids_arr = explode('_', $attr_ids);
            if ($index == 0) {
                $first_attribute_ids = $attr_ids_arr;
            }
            $goods_attr_ids[] = $attr_ids_arr;
            foreach ($attr_ids_arr as $key => $valuex) {
                $goods_attr_arr_temp[] = intval($valuex);
            }
            $goods_limit = $value['goods_limit'];
            if (!empty($goods_limit)) {
                $value['goods_storage'] = $goods_limit;
            }
            if (!empty($userInfo['user_id'])) {
                $num = OrderItemModel::getBuyNumber($goods_id, $value['attribute_ids'], $userInfo['user_id']);
                if (!empty($goods_limit)) {
                    if ($goods_limit <= $num) {
                        $value['goods_storage'] = 0;
                    }
                }
            }
            if (intval($goods['goods_special']) == 0) {
                $value['goods_return_price'] = round(($value['goods_ratio_price']) * 0.05, 2);
            }
            $goods_common_list_out[] = $value;
        }
        foreach ($goods_common_list_out as &$value) {
            $value['disabled'] = false;
            if (!in_array($value['attribute_ids'], $goods_attr_arr_temp)) {
                $value['disabled'] = true;
            }
            if (in_array($value['attribute_ids'] . "", $first_attribute_ids)) {
                $value['selected'] = true;
            }
        }
        foreach ($attr_list as &$value) {
            $list = $value['list'];
            foreach ($list as &$item) {
                if (!in_array($item['id'], $goods_attr_arr_temp)) {
                    $item['disabled'] = true;
                }
                if (in_array($item['id'] . "", $first_attribute_ids)) {
                    $item['selected'] = true;
                }
            }
            $value['list'] = $list;
        }
        GoodsModel::readAdd($goods_id);
        if (isset($userInfo['user_id'])) {
            $user_collect_up_model = new UserCollectUpModel();
            //登录
            $goods['is_collect'] = ($user_collect_up_model->getChildInfo($userInfo['user_id'], $goods_id, 1)) ? true : false;//收藏
            $goods['is_up'] = ($user_collect_up_model->getChildInfo($userInfo['user_id'], $goods_id, 2)) ? true : false;//点赞
        } else {
            //未登录
            $goods['is_collect'] = false;
            $goods['is_up'] = false;
        }
        $store = StoreModel::getStoreInfo($goods['store_id'], "id,store_name,contact_phone,invoice,delivery");
        $res['goods'] = $goods;
        if (!empty($store['delivery'])) {
            $time = strtotime('+1 day');
            if (date("H") == 23) {
                $time = strtotime('+2 day');
            }
            $store['delivery'] = str_replace("day", date("n月j日", $time), $store['delivery']);
        }
        $res['store'] = $store;
        $res['attr_list'] = $attr_list;
        $res['cart_list'] = $cart_list;
        $res['goods_common_list'] = $goods_common_list_out;
        $res['goods_attr_ids'] = $goods_attr_ids;
        return self::returnMsg(1, $res);
    }

    /**
     * 回去商品分类一级分类
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTypeFirst()
    {
        $map = [
            'parent_id' => 0,
            'status' => 0,
            'special' => 0
        ];
        $type_model = new GoodsTypeModel();
        $type_list = $type_model->where($map)->field('id,name,img,parent_id,sort')->order('sort desc')->select();
        return self::returnMsg(1, $type_list);
    }

    /**
     * 商品二级分类
     * @param int $parent_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTypeSecond($parent_id = 0)
    {
//        $map = [
//            'parent_id' => $parent_id,
//            'status' => 0
//        ];
        $field = "id,name,img,parent_id,sort";
//        $goodsModel = new GoodsModel();
//        $type_model = new GoodsTypeModel();
        $list = GoodsTypeModel::getChildList($parent_id, $field, 0, 0);
        return self::returnMsg(1, $list);
//        $listIds = Util::getChildrenIds($list);
//        $out_list = [];
//        foreach ($listIds as $key => $value) {
//            $map_temp = [
//                'goods_status' => 1,
//                'whereIn' => [
//                    'field' => 'goods_type_id',
//                    'condition' => $value['ids_str'],
//                ]
//            ];
//            $res = $goodsModel->getListCommonIn($map_temp, "id DESC", 1000, 'id,goods_title,goods_img,goods_min_price,goods_min_unit,goods_max_price', '', $this->currentUser['user_id']);
//            if (empty($store_id)) {
//                if (count($res) > 0) {
//                    $out_list[$key]['goodslist'] = $res;
//                    $out_list[$key]['title'] = $value['title'];
//                }
//            } else {
//                if (count($res) > 0) {
//                    $item = [
//                        'goodslist' => $res,
//                        'title' => $value['title']
//                    ];
//                    $out_list[] = $item;
//                }
//            }
//        }
//        return self::returnMsg(1, $out_list);
    }

    /**
     * 商品二级分类
     * @param int $parent_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTypeSecondOld($parent_id = 0)
    {
        $userInfo = $this->currentUser;//登录信息
        if (!isset($userInfo['user_id'])) {
            $userInfo['user_id'] = 0;
        }
        $map = [
            'parent_id' => $parent_id,
            'status' => 0
        ];
        $field = "id,name,img,parent_id,sort";
        $goodsModel = new GoodsModel();
        $type_model = new GoodsTypeModel();
        $data = $type_model->where($map)->field($field)->select();
        $list = Util::levelTreeChildren($data, $parent_id);
        Util::listOrder($list, 'sort', 'desc', 'number');
        $listIds = Util::getChildrenIds($list);
        $out_list = [];
        foreach ($listIds as $key => $value) {
            $map_temp = [
                'goods_status' => 1,
                'whereIn' => [
                    'field' => 'goods_type_id',
                    'condition' => $value['ids_str'],
                ]
            ];
            $res = $goodsModel->getListCommonIn($map_temp, "id DESC", 1000, 'id,goods_title,goods_img,goods_min_price,goods_min_unit,goods_max_price', '', $userInfo['user_id']);
            if (empty($store_id)) {
                if (count($res) > 0) {
                    $out_list[$key]['goodslist'] = $res;
                    $out_list[$key]['title'] = $value['title'];
                }
            } else {
                if (count($res) > 0) {
                    $item = [
                        'goodslist' => $res,
                        'title' => $value['title']
                    ];
                    $out_list[] = $item;
                }
            }
        }
        return self::returnMsg(1, $out_list);
    }

    /**
     * 获取商品购买清单
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGoodsInventory()
    {
        $user_collect_up_model = new UserCollectUpModel();
        $map = [
            'a.user_id' => $this->currentUser['user_id'],
            'a.type' => 1,
            'g.delete_time' => 0,
            'g.goods_status' => 1
        ];
        $goods_ids = $user_collect_up_model->alias('a')->join("t_goods g", "a.goods_id=g.id")->where($map)->field('a.goods_id,a.goods_first_type')->select();
        if (empty($goods_ids)) {
            $type_list[] = [
                'id' => 0,
                'title' => "我的清单",
                'goodslist' => []
            ];

            return self::returnMsg(1, $type_list);
        }
        $goods_ids_arr = [];
        $goods_type_arr = [];
        foreach ($goods_ids as $key => $value) {
            $goods_ids_arr[] = $value['goods_id'];
            $goods_type_arr[] = $value['goods_first_type'];
        }
        //去除重复数组
        $goods_type_arr = array_unique($goods_type_arr);
        $goods_type_mpdel = new GoodsTypeModel();
        $goods_type_list = $goods_type_mpdel->whereIn('id', $goods_type_arr)->field('id,name')->select();
        $map_temp = [
            'goods_status' => 1,
            'whereIn' => [
                'field' => 'id',
                'condition' => implode(",", $goods_ids_arr),
            ]
        ];
        $goodsModel = new GoodsModel();
        $res = $goodsModel->getListCommonIn($map_temp, "id DESC", 1000, 'id,goods_title,goods_first_id,goods_title,goods_img,goods_min_price,goods_max_price,goods_min_unit,goods_max_unit', '', $this->currentUser['user_id']);

        $type_list[] = [
            'id' => 0,
            'title' => "我的清单",
            'goodslist' => $res
        ];
        if (count($res) == 0) {
            return self::returnMsg(1, $type_list);
        }
        $list_goods = [];
        foreach ($res as $key => $value) {
            if (isset($list_goods[$value['goods_first_id']])) {
                $list_goods[$value['goods_first_id']][] = $value;
            } else {
                $list_goods[$value['goods_first_id']] = [];
                $list_goods[$value['goods_first_id']][] = $value;
            }
        }
        foreach ($goods_type_list as $key => $value) {
            $goods_list = isset($list_goods[$value['id']]) ? $list_goods[$value['id']] : [];
            $type_list[] = [
                'id' => $value['id'],
                'title' => $value['name'],
                'goodslist' => $goods_list
            ];
        }
        return self::returnMsg(1, $type_list);
    }

    /**
     * 分享转发 更新数据
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onShareAdd(Request $request)
    {
        $goods_id = $request->param("goods_id");
        $ret = GoodsModel::shareAdd($goods_id);
        if ($ret) {
            return self::returnMsg(1, [], "转发成功");
        }
        return self::returnMsg(0, [], "转发失败");
    }

    /**
     * 获取推广商品二维码
     * @param Request $request
     * @return \think\response\Json
     */
    public function onCreateQRcode(Request $request)
    {
        $goods_id = $request->param("goods_id");
        $code = $request->param("code");
        $path = $request->param("path");
        $redis = $this->model->redis;
        $redis_key = $this->model->redis_key;
        $id = $redis->hGet($redis_key, $goods_id . "_code");
        if (!empty($id)) {
            $url_img = $redis->hGet($redis_key, $goods_id . '_' . $code);
            if (!empty($url_img)) {
                return self::returnMsg(1, $url_img, "获取缓存数据");
            }
        }
        $wx_param = new WxParam();
        $poster = "./goods_img/generalize/" . $goods_id . ".png";//存储路径
        if (!file_exists($poster)) {
            $ret = $this->model->createGeneralizeImg($goods_id);
            if ($ret === false) {
                return self::returnMsg(0, [], "获取失败");
            }
        }
        $url = $wx_param->getSceneQrcode($goods_id . '_' . $code, $path);
        $file_name = "goods_img/generalize/" . $goods_id . '_' . $code . ".png";//存储路径
        $save_name = "./goods_img/generalize/" . $goods_id . '_' . $code . ".png";//存储路径
        $image = Image::open($poster);
        $font = getcwd() . '/msyh.ttf';//字体
        $image->water($url, array(100, 1020));//小程序图片
        $image->text("回家相迎的温馨", $font, 28, '#27292a', 1, array(440, 1120));//小程序说明
        $image->text("长按识别·去逛逛", $font, 20, '#b1b0b0', 1, array(440, 1190))->save($save_name);//小程序说明
        $res = Oss::moveOssFile($file_name, $save_name);
        if ($res['code'] == 1) {
            $redis->hSet($redis_key, $goods_id . "_code", $goods_id);
            $url_img = $res['url'];
            unlink($save_name);
            $redis->hSet($redis_key, $goods_id . '_' . $code, $url_img);
        }
        return self::returnMsg($res['code'], $res['url'], $res['msg']);
    }

}
